use crate::database::db_conn;
use crate::CustomResult::*;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow; // 数据库连接

/************************** 实体  ***************************/

#[derive(Debug, FromRow, Serialize, Deserialize, Default, Clone)]
pub struct Divination {
    pub id: i32,
    pub number: Option<String>,              //签号 eg. 第一签
    pub name: Option<String>,                //签名 eg. 悔过自新
    pub level: Option<String>,               //签级 eg. 上上签
    pub poem: Option<String>,                //签诗
    pub poem_interpretation: Option<String>, //诗解
    pub career_prediction: Option<String>,   //事业
    pub love_prediction: Option<String>,     //爱情
    pub created_time: Option<DateTime<Utc>>, //抽签时间
    pub user_id: Option<i32>,                //抽签人
    pub remark: Option<String>,              //备注
}


/************************** 查询详情 by id  ***************************/
pub async fn find_by_id(id: i32) -> CustomResult<Divination> {

    //连接到数据库
    let pool = db_conn::get_pool()
        .await
        .map_err(CustomError::from)?;

    // 根据id 查询
    let row = sqlx::query_as::<_, Divination>("SELECT * FROM t_divination WHERE id = ?")
        .bind(id)
        .fetch_one(&pool)
        .await
        .map_err(CustomError::from)?;
    Ok(row)
}

/************************** 插入 by gpt  ***************************/
pub async fn insert(
    number: &str,
    name: &str,
    level: &str,
    poem: &str,
    poem_interpretation: &str,
    career_prediction: &str,
    love_prediction: &str,
    user_id: i32,
    remark: &str,
) -> CustomResult<u64> {

    // 连接到数据库
    let pool = db_conn::get_pool()
        .await
        .map_err(CustomError::from)?;

    // 执行插入操作
    let res = sqlx::query!(
        "INSERT INTO t_divination (number, name, level, poem, poem_interpretation, career_prediction, love_prediction, user_id, remark) VALUES (?, ?, ?, ?, ?, ?, ? ,?, ?)",
        number,
        name,
        level,
        poem,
        poem_interpretation,
        career_prediction,
        love_prediction,
        user_id,
        remark
    )
    .execute(&pool)
    .await
    .map_err(CustomError::from)?
    .last_insert_id();
    Ok(res)
}

/************************** 获取指定用户 今日已抽签的数量  ***************************/
pub async fn get_user_today_divination_count(user_id: i32) -> CustomResult<i64> {
    // 连接到数据库
    let pool = db_conn::get_pool()
        .await
        .map_err(CustomError::from)?;

    // 执行查询并获取今日抽签数量
    let count: i64 = sqlx::query_scalar("SELECT COUNT(*) AS divination_count
                 FROM t_divination
                 JOIN t_user ON t_divination.user_id = t_user.id
                 WHERE t_divination.user_id = ?
                 AND DATE(t_divination.created_time) = CURRENT_DATE")
        .bind(user_id)
        .fetch_one(&pool)
        .await
        .map_err(CustomError::from)
        .unwrap_or(0); // 如果查询结果为 None，返回 0

    // 输出 divination_count 值
    println!("divination_count={}", count);

    // 根据 divination_count 的值返回结果
    if count < 3 {
        Ok(count)
    } else {
        Err("今日抽签次数大于3次".into())
    }
}